<?php

namespace addons\shopro\library\teams;

use addons\shopro\controller\User;
use addons\shopro\library\commission\Agent;
use addons\shopro\library\commission\Log;
use addons\shopro\library\teams\Config;
use addons\shopro\library\Oper;
use addons\shopro\library\commission\Config as commissionConfig;
use addons\shopro\model\commission\Order as OrderModel;
use addons\shopro\model\commission\Reward as RewardModel;
use addons\shopro\model\User as UserModel;
use app\admin\model\shopro\teams\Config as TeamsConfigModel;
use app\admin\model\shopro\teams\Order as TeamsOrderModel;
use app\admin\model\shopro\teams\Reward as TeamsRewardModel;



/**
 * 分佣业务
 */
class Commission
{

    public $_config;    // 团队设置
    public $item;       // 订单商品
    public $buyer;      // 购买人
    public $amount = 0;     // 订单商品核算价格
    public $_commissionConfig;    // 分销设置

    // 团队状态
    const TWMAS_CLOSE = 0;  // 团队中心已关闭
    /**
     * 构造函数
     * 
     * @param array      $item     分销商品
     */
    public function __construct($item)
    {
        $this->buyer = new Agent($item['user_id']);
        $this->item = $item;
        $this->_config = new Config();
        $this->_commissionConfig = new commissionConfig();
    }

    /**
     * 检测有没有团购奖励
     *
     * @return void
     */
    public function checkTeams()
    {
        // 未找到订单商品或购买人
        if (!$this->item || !$this->buyer->user) {
            return false;
        }

        $config = TeamsConfigModel::column('value', 'name');

        // 团队中心已关闭
        if (self::TWMAS_CLOSE === intval($config['team_dividend'])) {
            return false;
        }

        //看看是否设置 团队奖励
        if(!isset($config['team_reward_rate']) || $config['team_reward_rate'] <= 0) {
            return false;
        }
        
        $userInfo =  UserModel::get($this->buyer->user->id);
        //没有团长也不参与奖励
        if($userInfo['heads_sid'] ==0) {
            return false;
        }

        // 获取商品结算价格（四舍五入精确到分）
        $this->amount = $this->getGoodsCommissionAmount();
        // 没有分润的必要了
        if ($this->amount <= 0) {
            return false;
        }
        return true;
    }

    // 获取商品核算总金额
    public function getGoodsCommissionAmount()
    {
        $commissionType = $this->_commissionConfig->getCommissionPriceType();
        $amount = round(0, 2);
        switch ($commissionType) {
            case 'pay_price':
                $amount = $this->item['pay_price'];
                break;
            case 'goods_price':
                $amount = round($this->item['goods_price'] * $this->item['goods_num'], 2);
                break;
        }
        return $amount;
    }

    /**
     *
     *  添加团队分红订单
     *    2023.6.1
     */
    public function addTeamsOrder()
    {
        $commissionOrder = TeamsOrderModel::where('order_item_id', $this->item['id'])->find();
        // 已添加过分销订单
        if ($commissionOrder) {
            return $commissionOrder;
        }

        $config = TeamsConfigModel::column('value', 'name');

        $commission_rules =[
            'rate'=> $config['team_reward_rate'],
        ];

        $headsUser = UserModel::where('id', $this->buyer->user->heads_sid)->find();
        // 自己的团长是高级团长 执行高级佣金
        if($headsUser->is_high_heads == 1){
            $commission_rules =[
                'rate'=> $config['high_team_reward_rate'],
            ];
        }
        $userInfo =  UserModel::get($this->buyer->user->id);
        $commissionOrderParams = [
            'order_id' => $this->item['order_id'],
            'order_item_id' => $this->item['id'],
            'buyer_id' => $this->buyer->user->id,
            'goods_id' => $this->item['goods_id'],
            'amount' => $this->amount,
            'commission_price_type' => $this->_commissionConfig->getCommissionPriceType(),
            'commission_rules' => json_encode($commission_rules),  // 记录当前设置的分佣规则，防止以后系统或者分销商设置有变导致更改历史规则
            'commission_event' => $this->_commissionConfig->getCommissionEvent(),
            'heads_sid' => $userInfo['heads_sid']
        ];
        $commissionOrder = TeamsOrderModel::create($commissionOrderParams);

        return $commissionOrder;
    }

    /**
     * 执行团队奖励计划
     *
     * @param object    $commissionOrder           分销订单
     */
    public function runTeamsPlanNew($commissionOrder)
    {
        // 防止重复添加团队佣金
        $commissionReward = TeamsRewardModel::get([
            'teams_order_id' => $commissionOrder->id,
            'heads_sid' => $commissionOrder->heads_sid,
        ]);

        if (!$commissionReward) {
            $commissionLevelRule['rate'] = json_decode($commissionOrder->commission_rules,true)['rate'] ?? 0;
            $commission = $this->caculateGoodsCommission($commissionLevelRule, round($this->amount / $this->item['goods_num'], 2), 1);
            if ($commission > 0) {
                $commissionRewardParams = [
                    'order_id' => $commissionOrder->order_id,
                    'order_item_id' => $commissionOrder->order_item_id,
                    'buyer_id' => $commissionOrder->buyer_id,      // 购买人
                    'teams_order_id' => $commissionOrder->id,   // 团队订单ID
                    'type' => 'money',                               // 奖金类型
                    'commission' => $commission,                     // 佣金
                    'status' => 0,                              // 佣金状态
                    'original_commission' => $commission,            // 原始佣金
                    'commission_rules' => json_encode($commissionLevelRule),   // 分佣层级
                    'heads_sid'=>$commissionOrder->heads_sid,
                ];
                $commissionReward =  TeamsRewardModel::create($commissionRewardParams);
                Log::write($commissionOrder->heads_sid, 'team', [
                    'action' => 'payed',
                    'reward' => $commissionReward,
                ], ['oper_type' => 'user', 'oper_id' => $commissionOrder->buyer_id]);
                
            }
            return true;

        }
    }

    /**
     * 计算对应规则分销佣金
     *
     * @param int $commissionRule      分销规则
     * @param int $amount              结算价格
     * @param int $goodsNum            购买数量
     */
    public function caculateGoodsCommission($commissionRule, $amount, $goodsNum = 1)
    {
        $commission = 0;
        if (isset($commissionRule['rate']) && $commissionRule['rate'] > 0) {
            $commission = round($amount * $commissionRule['rate'] * 0.01, 2);
        }
        if (isset($commissionRule['money']) && $commissionRule['money'] > 0) {
            $commission = $commissionRule['money'] * $goodsNum;
        }
        return number_format($commission, 2, '.', '');
    }
}
